package gui;

import alarm.Alarm;
import java.util.Timer;
import javax.swing.*;

import gui.user;
import gui.HintTextFieldUI;

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class Login extends JFrame {

	public static String user;
	public static final String conf_dir = "conf\\";
	public static final String data_dir = "task\\";
	static final String userRegister = "userRegister.txt";
	JButton blogin = new JButton("Login");
	JButton bsignup = new JButton("Sign up");
	JPanel panel = new JPanel();
	JTextField txuser = new JTextField("testing", 15);
	JPasswordField pass = new JPasswordField("12345", 15);
	JLabel username = new JLabel("Username:");
	JLabel password = new JLabel("Password:");
	JFrame frame = new JFrame();
	ArrayList<user> list = new ArrayList<user>();
	File file = new File(conf_dir + userRegister);

	public Login() {
		super("Login Authentication");
		setSize(600, 400);
		setLocation(500, 280);
		setResizable(false);
		panel.setLayout(null);
		check_dir();
		readFromFile();

		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				try {
					writeToFile();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				System.exit(0);
			}
		});

		/* Here you can change the location & size */
		username.setBounds(120, 180, 150, 20);
		password.setBounds(120, 230, 150, 20);
		txuser.setBounds(200, 180, 200, 20);
		pass.setBounds(200, 230, 200, 20);
		blogin.setBounds(200, 280, 80, 20);
		bsignup.setBounds(320, 280, 80, 20);
		panel.add(blogin);
		panel.add(bsignup);
		panel.add(username);
		panel.add(txuser);
		panel.add(password);
		panel.add(pass);
		panel.setOpaque(false);
		JPanel loginBgPanel = new LoginBgPanel();
		loginBgPanel.setLayout(new BorderLayout());
		loginBgPanel.add(panel, BorderLayout.CENTER);
		getContentPane().add(loginBgPanel);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);

		bsignup.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				final JTextField txuser1 = new JTextField(15);
				final JPasswordField pass1 = new JPasswordField(15);
				final JFrame frame1 = new JFrame();
				frame1.setBounds(320, 140, 320, 180);
				frame1.setLayout(new GridLayout(4, 2));
				frame1.setResizable(false);
				final JPanel jp1 = new JPanel();
				frame1.add(jp1);
				txuser1.setUI(new HintTextFieldUI("More than 5 words", true));
				pass1.setUI(new HintTextFieldUI("More than 5 words", true));
				JLabel jl1 = new JLabel("User Name:");
				jp1.add(jl1);
				jp1.add(txuser1);
				JPanel jp2 = new JPanel();
				frame1.add(jp2);
				JLabel jl2 = new JLabel("Password: ");
				jp2.add(jl2);
				jp2.add(pass1);
				JPanel jp5 = new JPanel();
				frame1.add(jp5);
				JButton bsign = new JButton("Sign up");

				jp5.add(bsign);

				frame1.setVisible(true);

				bsign.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent ae) {
						user user = new user();

						if (txuser1.getText().length() < 5
								|| (new String(pass1.getPassword())).length() < 5) {
							JOptionPane.showMessageDialog(null,
									"The username or password is too short.");
						} else {
							JOptionPane.showMessageDialog(
									null,
									"Registration successful"
											+ user.getUserName());
							user.setUserName(txuser1.getText());
							user.setPassWord(new String(pass1.getPassword()));
							list.add(user);
							try {
								writeToFile();
								frame1.dispose();
							} catch (IOException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
					}
				});
				txuser1.addKeyListener(new KeyAdapter() {
					public void keyTyped(KeyEvent e) {
						char c = e.getKeyChar();
						if (!(Character.isDigit(c) || Character.isAlphabetic(c)
								|| (c == KeyEvent.VK_BACK_SPACE)
								|| (c == KeyEvent.VK_DELETE) || (c == KeyEvent.VK_ENTER))) {
							e.consume();
							JOptionPane.showMessageDialog(null,
									"Only text & number");
						}
					}
				});
				pass1.addKeyListener(new KeyAdapter() {
					public void keyTyped(KeyEvent e) {
						char c = e.getKeyChar();
						if (!(Character.isDigit(c) || Character.isAlphabetic(c)
								|| (c == KeyEvent.VK_BACK_SPACE)
								|| (c == KeyEvent.VK_DELETE) || (c == KeyEvent.VK_ENTER))) {
							e.consume();
							JOptionPane.showMessageDialog(null,
									"Only text & number");
						}
					}
				});
			}
		});

		blogin.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				try {
					user temp = new user(txuser.getText(), new String(pass
							.getPassword()));
					match(temp);
				} catch (Exception e1) {
					e1.printStackTrace();
				}

			}
		});
	}

	private void readFromFile() {
		try {
			FileInputStream fis = new FileInputStream(file);
			ObjectInputStream ois = new ObjectInputStream(fis);
			user read = null;
			try {
				while (true) {
					read = (user) ois.readObject();
					if (read == null) {
						break;
					}
					list.add(read);
				}
			} catch (Exception e) {
			}
			fis.close();
			ois.close();

		} catch (FileNotFoundException e) {

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void writeToFile() throws IOException {
		try (ObjectOutputStream oos = new ObjectOutputStream(
				new FileOutputStream(file, false))) {
			for (user usr : list) {
				oos.writeObject(usr);
			}
			oos.flush();
			oos.close();
		} catch (FileNotFoundException e) {
			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e1) {

					e1.printStackTrace();
				}
			}
		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	private void match(user user) {
		boolean match = false;
		for (user usr : list) {
			if (usr.getUserName().equals(user.getUserName())
					&& usr.getPassWord().equals(user.getPassWord())) {
				JOptionPane.showMessageDialog(null, "Successful");
				txuser.setText("");
				pass.setText("");
				Login.user = new String(user.getUserName());
				JFrame regFace = new Calendar1();
				regFace.setVisible(true);
				dispose();
				match = true;				
				break;
			}
		}
		if (!match) {
			JOptionPane.showMessageDialog(null, "Wrong Password / Username");
			txuser.setText("");
			pass.setText("");
			txuser.requestFocus();
		}
		if(match){
			 Timer timer = new Timer();
			 timer.schedule(new Alarm(), 0, 10000);
		}
	}
	
	private void check_dir(){
		File f = new File(conf_dir);
		if (!f.exists() || !f.isDirectory())
			f.mkdir();
		f = new File(data_dir);
		if (!f.exists() || !f.isDirectory())
			f.mkdir();
	}

	public static void main(String[] args) {
		Frame frameTabel = new Login();
		frameTabel.setVisible(true);
	}

}